import React, { useState } from 'react';
import { Form, Input, Button, Row, Col } from 'antd';

import { verificationCodeApi } from '@/api';
import { showSuccessMessageDebounce } from '@/utils/message';
import { storageUserInfo } from '@/utils/user';
import { UserState, userLogin } from '@/services/user';
import PwdInput from '@/components/PwdInput';
import Code from '@/components/Code';

import style from './index.less';

const tailLayout = {
  wrapperCol: { span: 24 },
};

const Login: React.FC<any> = () => {
  // 密码显示隐藏

  const [loading, setLoading] = useState<boolean>(false);

  // 验证码
  const codeUrl = () => {
    return `${verificationCodeApi}?timestampe=${+new Date()}`;
  };

  // 登录请求
  const loginRequest = (params: UserState) => {
    userLogin(params)
      .then(res => {
        showSuccessMessageDebounce('登录成功');
        const { token } = res.data.data;
        // 存储用户信息
        storageUserInfo({
          username: params.account,
          access_token: token,
        });
        // 跳转
        window.location.href = '/';
      })
      .finally(() => {
        setLoading(false);
      });
  };

  // 校验通过登录
  const onFinish = (values: any) => {
    setLoading(true);
    loginRequest(values);
  };

  return (
    <div className={style.main}>
      <div className={style.form}>
        <h3>登录</h3>
        <Form name="basic" onFinish={onFinish} layout="vertical">
          <Form.Item
            label="用户名"
            name="account"
            rules={[{ required: true, message: '请输入用户名！' }]}
          >
            <Input size="large" placeholder="请输入用户名" />
          </Form.Item>

          <PwdInput size="large" />

          <Form.Item
            label="验证码"
            name="code"
            rules={[{ required: true, message: '请输入验证码！' }]}
          >
            <Row>
              <Col span={14}>
                <Input size="large" placeholder="请输入验证码" />
              </Col>
              <Col span={9} offset={1}>
                <Code url={codeUrl()} />
              </Col>
            </Row>
          </Form.Item>

          <Form.Item {...tailLayout}>
            <Button
              type="primary"
              htmlType="submit"
              size="large"
              loading={loading}
            >
              登录
            </Button>
          </Form.Item>
        </Form>
      </div>
    </div>
  );
};
export default Login;
